<?php

namespace app\api\server;

use app\api\server\Address as ServerAddress;
use app\api\server\Cart as ServerCart;
use app\api\server\Goods as ServerGoods;
use app\api\server\User as ServerUser;
use app\common\controller\Server;
use app\common\library\Auth;
use app\common\model\Cart;
use app\common\model\goods\Goods as GoodsGoods;
use app\common\model\goods\Review;
use app\common\model\MoneyLog;
use app\common\model\order\Goods;
use app\common\model\order\Order as OrderOrder;
use app\common\model\order\Refund;
use app\common\model\order\Trade;
use app\common\model\performance\Log;
use app\common\model\User;
use app\common\model\user\Address;
use think\Db;
use think\Exception;

/**
 * 订单逻辑
 */
class Order
{

    /**
     * 下单预览
     *
     */
    public static function yu_order($data, $userinfo)
    {
        extract($data);
        try {
            //地址信息
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get($address_id);
                $goods['addressInfo'] = $addressInfo;
                $goods['address_id']  = $address_id;
            } else {
                $addressInfo = ServerAddress::getDefaultAddress($userinfo->id);
                if ($addressInfo) {
                    $goods['addressInfo'] = $addressInfo;
                    $goods['address_id']  = $addressInfo['id'];
                }
            }

            if ($type == 2) {
                $cart_ids = ServerCart::addCart([
                    'goods_id' => $goods_id,
                    'num' => $num,
                    'unit' => $unit,
                    'add_sub' => 0,
                ], $userinfo->id, 2);
            }
            $goods['goods_lists'] =  ServerCart::getGoods($cart_ids, $userinfo);
            $goods['cart_ids'] = $cart_ids;
            $goods['userInfo'] = $userinfo;
            if ($pay_type == 1) {
                $goods['total_fee'] = array_sum(array_column($goods['goods_lists'], 'pay_fee'));
            } else {
                if ($userinfo['group_id'] > 1) {
                    $goods['total_fee'] = array_column($goods['goods_lists'], 'pay_fee')[0];
                } else {
                    $goods['total_fee'] = array_sum(array_column($goods['goods_lists'], 'pay_fee'));
                }
            }
            $goods['total_num'] = array_sum(array_column($goods['goods_lists'], 'num'));
            $goods['discount_amount'] = array_sum(array_column($goods['goods_lists'], 'discount_amount'));
            $goods['performance'] = array_sum(array_column($goods['goods_lists'], 'performance'));
            if ($type == 2) {
                Cart::whereIn('id', $cart_ids)->where('user_id', $userinfo['id'])->delete();
            }
            return $goods;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }

    /**
     * 订单下单
     *
     */
    public static function add_order($data)
    {
        extract($data);

        Db::startTrans();
        try {
            if (!isset($address_id) || !$address_id) {
                exception('请选择收货地址');
            }
            if (!isset($goods_lists) || !$goods_lists) {
                exception('请选择购买商品');
            }
            $order = OrderOrder::create([
                'user_id' => $userInfo['id'],
                'sn' => sn('order', 'sn', 'NO'),
                'total_num' => $total_num,
                'address_id' => $address_id,
                'contact' => $addressInfo['contact'],
                'telephone' => $addressInfo['telephone'],
                'address' => $addressInfo['detailed_address'],
                'total_fee' => $pay_type == 1 ? $total_fee : 0,
                'total_fee_range' => $pay_type != 1 ? $total_fee : 0,
                'discount_amount' => $pay_type == 1 ? $discount_amount : 0,
                'type' => $pay_type,
                'content' => $content,
                'usedate' => $usedate,
                'performance' => $performance,
            ], true);
            foreach ($goods_lists as $vv) {
                Goods::create([
                    'order_id' => $order['id'],
                    'goods_id' => $vv['goods_id'],
                    'goods_num' => $vv['num'],
                    'goods_name' => $vv['goods']['title'],
                    'goods_price' => $pay_type == 1 ? $vv['goods']['price'] : 0,
                    'subtotal_range' => $pay_type != 1 ? $vv['pay_fee'] : '',
                    'goods_price_range' => $pay_type != 1 ? $vv['goods']['price_range']: '',
                    'goods_unit' => $vv['unit'],
                    'image' =>  $vv['goods']['image'],
                    'subtotal' => $pay_type == 1 ? bcsub($vv['pay_fee'], $vv['discount_amount'], 2)  : 0,
                ]);
                ServerGoods::reduceInventory($vv['goods_id'],$vv['num']);
            }
            Cart::whereIn('id', $cart_ids)->where('user_id', $userInfo['id'])->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return $order->id;
    }


    //用户订单
    static  function order_list($data)
    {
        extract($data);
        $auth=  Auth::instance();
        $order = new OrderOrder();
        if ($order_status != 'all') {
            $order->where('order_status', $order_status);
        }
        return $order->with(['goods'])->where('user_id',$auth->id)->order('id desc')->paginate();
    }
    //确认收货
    static public function take_order($data)
    {
        extract($data);
        Db::startTrans();
        try {
            $order = OrderOrder::get($id);
            if ($order->order_status < '20') {
                exception('订单状态错误');
            }
            $order->order_status = '30';
            $order->taketime = time();
            $order->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return true;
    }
    //支付成功添加业绩
    static public function add_performance($order)
    {
        $ordergoods = Goods::all(['order_id' => $order->id]);
        if (!$ordergoods) {
            return true;
        }
        $userinfo = User::get($order->user_id);

        foreach ($ordergoods as $k => $v) {
            $goods = GoodsGoods::get($v->goods_id);
            $goods->sales_volume = $v->subtotal;
            $goods->save();
            $users = User::whereIn("id", $userinfo['paren_ids'])->where('group_id', '>', $userinfo['group_id'])->order('id desc')->select();
            if ($users) {
                foreach ($users as $vv) {
                    Log::create([
                        'user_id' => $vv['id'],
                        'u_id' => $userinfo['id'],
                        'order_id' => $order->id,
                        'goods_id' => $v['goods_id'],
                        'o_g_id' => $v['id'],
                        'num' => $v['goods_num'],
                        'performance' => $v['subtotal'],
                        'user_group_id' => $vv['group_id'],
                        'u_group_id' => $userinfo['group_id'],
                    ]);
                }
            }
        }
    }

    static public function goods_evaluate($data)
    {
        extract($data);
        $ids = OrderOrder::where('user_id', $uid)->where('order_status', '30')->column('id');
        $lists = Goods::with(['review'])->whereIn('goods.order_id', $ids)->where('evaluate', $evaluate)->paginate();
        return $lists;
    }
    static public function evaluate($data)
    {
        extract($data);
        Db::startTrans();
        try {
            Review::create([
                'user_id' => $uid,
                'goods_id' => $goods_id,
                'description' => $description,
                'description' => $description,
                'images' => $images,
                'order_id' => $order_id,
                'star' => $star,
                'order_goods_id' => $order_goods_id,
            ]);
            Goods::where('id', $order_goods_id)->update(['evaluate' => 1]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return true;
    }
}
